let RouteModel = require('../model/ControllerModel')
const { userAPI, uploadExt, uploadMaxBuffer } = require('../configure')
const path = require('path')
const fs = require('fs')
const ErrorModel = require('../model/ErrorModel')

class Upload extends RouteModel {

  constructor () {super()}

  // 上传图片
  async create (ctx, next) {
    let file = ctx.request.files[0];
    const ext = path.extname(file.name),
          traceId = ctx.query.traceId;
    if (uploadExt.indexOf(ext) === -1) {
      throw(ErrorModel(500, '上传图片类型不支持', traceId))
    } else if (file.size > uploadMaxBuffer) {
      throw(ErrorModel(500, '上传图片不能超过5M', traceId))
    } else {
      let result = await this.request({
        url: `${userAPI}/biz/upload`,
        method: 'POST',
        formData: {
          name: "file",
          file: fs.createReadStream(file.path)
        },
        headers: {
          "token": "f84b6bf8f17608f8a82a69b5abdf02cd",
           "userId": "1",
           "requestId": "8a82a69b5abdf02",
           "udid": "82a69b5abdf02cd",
           "Content-Type": "multipart/form-data"
        }
      }, traceId)
      console.log(result)
    }
  }

}

module.exports = Upload
